package com.tnovoselec.android.travelassistant.fragment;

import java.util.List;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockFragment;
import com.tnovoselec.android.common.async.Async;
import com.tnovoselec.android.common.async.listener.Outcome;
import com.tnovoselec.android.common.async.notif.NotifierFactory;
import com.tnovoselec.android.travelassistant.Config;
import com.tnovoselec.android.travelassistant.R;
import com.tnovoselec.android.travelassistant.adapter.GasPricesAdapter;
import com.tnovoselec.android.travelassistant.async.DownloadGasPricesAsync;
import com.tnovoselec.android.travelassistant.dto.GasPriceDto;
import com.tnovoselec.android.travelassistant.dto.GasPricesResultHolder;

public class GasPricesFragment extends SherlockFragment{
	
	private ListView list;
	private GasPricesAdapter adapter;
	private Handler handler;
	private List<GasPriceDto> prices;
	private ProgressDialog progressDialog;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		adapter = new GasPricesAdapter(getActivity());
		handler = new Handler();
		getGasPrices();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.gas_prices, container, false);
		list = (ListView) v.findViewById(R.id.gas_prices_list);
		list.setAdapter(adapter);
		return v;
	}
	
	private void getGasPrices(){
		Async.doAsync(null, new DownloadGasPricesAsync(Config.GAS_PRICES_URL, getActivity(), false), new Outcome<Void, Boolean>() {

			@Override
			protected void succeeded(Void key, Boolean result) {
				prices =GasPricesResultHolder.getAll();
				adapter.setPrices(prices);
				if (progressDialog != null && progressDialog.isShowing()) {
					progressDialog.dismiss();
				}
			}

			@Override
			protected void failed(Void key, Throwable t) {
				if (progressDialog != null && progressDialog.isShowing()) {
					progressDialog.dismiss();
				}
				
			}
		}, NotifierFactory.newThreadSpecificNotifier(handler));
	}

}
